package com.pet.server.ext.action.user;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.Result;
import com.pet.server.ext.data.PetInfo;
import com.pet.server.ext.data.UserInfo;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.CookieHelper;
import com.pet.server.ext.util.JsonUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;
import com.pet.server.ext.util.cache.ConstantUtil;
public class Login extends ActionBase{
	
	public String userName,password,token;
	
	public Login(){
		 needCheckAuth =false;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		userName = params.getFieldValue("user_name");
		password = params.getFieldValue("password");
		token = params.getFieldValue("token");
		if(StringUtil.isEmpty(userName,password)){
			throw ApiError.Type.INVALID_PARAM.toException();
		}
	}
	
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		//UserInfo u = userService.findUserInfoByLogin(userName, MD5Util.MD5Encode(password, null));
		UserInfo u = userService.findUserInfoByLogin(userName, password);
		if(u==null){
        	throw ApiError.Type.INVALID_PARAM.toException("登录失败,用户名或者密码错误!");
        }
		if(!StringUtil.isEmpty(token)){
			userService.updateUserToken(token,user.user_id);
		}
		
		Result result = new Result();
		JSONObject o = new JSONObject();
		o.accumulate("user_name", u.user_name);
		o.accumulate("user_type", u.user_type);
		o.accumulate("nick_name", u.nick_name);
		o.accumulate("user_id", u.user_id);
		o.accumulate("score", u.score);
		o.accumulate("ico_path", u.ico_path);
		
		o.accumulate("phone_number", u.phone_number);
		List<PetInfo> list = userService.queryPetInfoByUserId(u.user_id);

		JSONArray array = new JSONArray();
		for(PetInfo pet:list){
			JSONObject so = new JSONObject();
			so.put("pet_id", pet.pet_id);
			so.put("name", pet.pet_name);
			so.put("ico_path", pet.ico_path);
			so.put("breed", pet.breed);
			so.put("breed_name", ConstantUtil.getInstance().getName(pet.breed));
			so.put("pet_cate", pet.pet_cate);
			so.put("birthday",JsonUtil.getTime(pet.create_time));
			array.add(so);
		}
		o.accumulate("pet_item", array);
		String cookie = CookieHelper.createCookie(u);
		JSONObject data = new JSONObject();
		data.put("data", o);
		result.setRet(data, cookie);
	    return result;
	}
}
